package com.ma.chapter8.countdownlatch;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

import static com.ma.util.Sleeper.sleep;

/**
 * @ClassName TestCyclicBarrier
 * @Author: mayongqiang
 * @DATE 2022/3/26 21:11
 * @Description:
 */
@Slf4j(topic = "m.TestCyclicBarrier")
public class TestCyclicBarrier {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(2);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            log.debug("task1,task2 finish.");
        });

        for (int i = 0; i < 3; i++) {
            service.submit(() -> {
                log.debug("task1 begin...");
                sleep(1);
                try {
                    cyclicBarrier.await();  //2-1=1
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
            service.submit(() -> {
                log.debug("task2 begin...");
                sleep(2);
                try {
                    cyclicBarrier.await();  //1-1=0
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });

        }

        service.shutdown();


    }

    private static void method1() {
        ExecutorService service = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 3; i++) {
            // 不可以重复使用
            CountDownLatch latch = new CountDownLatch(2);
            service.submit(() -> {
                log.debug("task1 start ...");
                sleep(1);
                latch.countDown();
            });
            service.submit(() -> {
                log.debug("task2 start ...");
                sleep(2);
                latch.countDown();
            });
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.debug("task1 task2 finish...");
        }
        service.shutdown();
    }
}
